#include "logindialog.h"
#include "ui_logindialog.h"
#include "tcpmgr.h"
#include <QRegularExpression>
LoginDialog::LoginDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::LoginDialog)
{
    ui->setupUi(this);
    connect(ui->reg_btn, &QPushButton::clicked, this, &LoginDialog::switchRegister);
    ui->forget_label->SetState("normal","hover","","selected","selected_hover","");
    ui->pass_edit->setEchoMode(QLineEdit::Password);

    ui->pass_visible->SetState("unvisible","unvisible_hover","","visible",
                               "visible_hover","");
    ui->login_btn->setCursor(Qt::PointingHandCursor);
    ui->reg_btn->setCursor(Qt::PointingHandCursor);
    ui->err_tip->clear();

    initHttpHandlers();
    connect(ui->pass_visible,&ClickedLabel::clicked,this,[this](){
         ClickLbState state = ui->pass_visible->GetCurState();
         if(state == ClickLbState::Normal){
             ui->pass_edit->setEchoMode(QLineEdit::Password);
         } else{
             ui->pass_edit->setEchoMode(QLineEdit::Normal);
         }
    });
    connect(ui->forget_label,&ClickedLabel::clicked,this,&LoginDialog::slotforgetpass);
    //连接登录回包信号
    connect(HttpMgr::GetInstance().get(), &HttpMgr::sig_login_mod_finish, this,
            &LoginDialog::slot_login_mod_finish);
    connect(this,&LoginDialog::sig_connect_tcp,TcpMgr::GetInstance().get(),&TcpMgr::slot_tcp_connect);
    connect(TcpMgr::GetInstance().get(),&TcpMgr::sig_con_success,this,&LoginDialog::slot_tcp_con_finish);
    connect(TcpMgr::GetInstance().get(), &TcpMgr::sig_login_fail, this, &LoginDialog::slot_login_fail);

}

LoginDialog::~LoginDialog()
{
    delete ui;
}

bool LoginDialog::checkPwdValid()
{
    auto pwd = ui->pass_edit->text();
    if(pwd.length() < 6 || pwd.length() > 15){
        qDebug() << "Pass length invalid";
        AddTip(TipErr::TIP_PWD_ERR, tr("密码长度应为6~15"));
        return false;
    }

    QRegularExpression regExp("^[a-zA-Z0-9!@#$%^&*]{6,15}$");
    bool match = regExp.match(pwd).hasMatch();
    if(!match){
        //提示字符非法
        AddTip(TipErr::TIP_PWD_ERR, tr("密码不能包含非法字符"));
        return false;;
    }
    DelTip(TipErr::TIP_PWD_ERR);
    return true;
}

bool LoginDialog::checkEmailValid()
{
    auto email = ui->email_edit->text();
    if(email.isEmpty()){
        qDebug() << "email empty " ;
        AddTip(TipErr::TIP_PWD_ERR, tr("请输入邮箱"));
        return false;
    }
    QRegularExpression regex(R"((\w+)(\.|_)?(\w*)@(\w+)(\.(\w+))+)");
    bool match = regex.match(email).hasMatch(); // 执行正则表达式匹配
    if(!match){
        //提示邮箱不正确
        AddTip(TipErr::TIP_EMAIL_ERR, tr("邮箱地址不正确"));
        return false;
    }
    DelTip(TipErr::TIP_EMAIL_ERR);
    return true;
}

void LoginDialog::enableBtn(bool a){
    ui->login_btn->setEnabled(a);
    ui->reg_btn->setEnabled(a);
}

void LoginDialog::AddTip(TipErr te, QString tips)
{
    _tip_errs[te] = tips;
    showTip(tips,false);
}

void LoginDialog::DelTip(TipErr te)
{
    _tip_errs.remove(te);
    if(_tip_errs.empty()){
        ui->err_tip->clear();
        return;
    }
}

void LoginDialog::showTip(QString str, bool b_ok)
{
    if(b_ok){
         ui->err_tip->setProperty("state","normal");
    }else{
        ui->err_tip->setProperty("state","err");
    }

    ui->err_tip->setText(str);

    repolish(ui->err_tip);
}

void LoginDialog::initHttpHandlers()
{
    //注册获取登录回包逻辑
    _handlers.insert(ReqId::ID_LOGIN_USER, [this](QJsonObject jsonObj){
        int error = jsonObj["error"].toInt();
        if(error != ErrorCodes::SUCCESS){
            showTip(tr("参数错误"),false);
            enableBtn(true);
            return;
        }
        auto email = jsonObj["email"].toString();
        //showTip(tr("登录成功"), true);
        //enableBtn(true);
        qDebug()<< "login email is " << email ;

        //发送信号通知tcpMgr发送长链接
        ServerInfo si;
        si.Uid = jsonObj["uid"].toInt();
        si.Host = jsonObj["host"].toString();
        si.Port = jsonObj["port"].toString();
        //si.Port = "8090";
        si.Token = jsonObj["token"].toString();

        _uid = si.Uid;
        _token = si.Token;
        qDebug()<< "email is " << email << " uid is " << si.Uid <<" host is "
                << si.Host << " Port is " << si.Port << " Token is " << si.Token;
        emit sig_connect_tcp(si);

    });
}



void LoginDialog::slotforgetpass()
{
    qDebug() << "slot to forgetpass";
    emit switchReset();
}

void LoginDialog::slot_login_mod_finish(ReqId id, QString res, ErrorCodes err)
{
    if(err != ErrorCodes::SUCCESS){
        showTip(tr("网络请求错误"),false);
        return;
    }
    // 解析 JSON 字符串,res需转化为QByteArray
    QJsonDocument jsonDoc = QJsonDocument::fromJson(res.toUtf8());
    //json解析错误
    if(jsonDoc.isNull()){
        showTip(tr("json解析错误"),false);
        return;
    }
    //json解析错误
    if(!jsonDoc.isObject()){
        showTip(tr("json解析错误"),false);
        return;
    }
    //调用对应的逻辑,根据id回调。
    _handlers[id](jsonDoc.object());
    return;
}

void LoginDialog::on_login_btn_clicked()
{
    if(!checkEmailValid()){
        return;
    }
    if(!checkPwdValid()){
        return;
    }

    enableBtn(false);
    auto email = ui->email_edit->text();
    auto pwd = ui->pass_edit->text();
    QJsonObject json_obj;
    json_obj["email"] = email;
    json_obj["pwd"] = pwd;
    HttpMgr::GetInstance()->PostHttpReq(gate_url_prefix+"/user_login",json_obj,ID_LOGIN_USER,LOGINMOD);
}

void LoginDialog::slot_tcp_con_finish(bool check)
{
    if(!check){
        qDebug()<<"连接失败";
        showTip(tr("网络请求错误"),false);
        enableBtn(true);
        return;
    }
    showTip(tr("聊天服务器连接成功，正在登录"),true);
    enableBtn(true);
    QJsonObject jsonobj;
    jsonobj["uid"] = _uid;
    jsonobj["token"] = _token;

    QJsonDocument doc(jsonobj);
    QByteArray jsonString = doc.toJson(QJsonDocument::Indented);
    //发送tcp请求给chat server
    TcpMgr::GetInstance()->sig_send_data(ReqId::ID_CHAT_LOGIN, jsonString);

}

void LoginDialog::slot_login_fail(int err)
{
    QString result = QString("登录失败, err is %1").arg(err);
    showTip(result,false);
    enableBtn(true);
}
